const getHandleValue = num => {
  return num < 10 ? `0${num}` : num;
}

export const dateFormat = (timestamps, startType) => {
  const d = new Date(timestamps);
  const year = d.getFullYear();
  const month = getHandleValue(d.getMonth() + 1);
  const day = getHandleValue(d.getDate());
  const hours = getHandleValue(d.getHours());
  const minutes = getHandleValue(d.getMinutes());
  const seconds = getHandleValue(d.getMinutes());

  let result = '';

  if (startType === 'year') {
    result = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  } else if (startType === 'yy-mm-dd') {
		result = `${year}-${month}-${day}`;
	} else if (startType === 'yy-mm') {
		result = `${year}-${month}`;
	} else {
    result = `${month}-${day} ${hours}:${minutes}:${seconds}`;
  }

  return result;
}

export const setLocal = (key, value) => {
  sessionStorage.setItem(key, value);
}

export const getLocal = (key) => {
  return sessionStorage.getItem(key) || '';
}

export const removeLocal = (key) => {
  return sessionStorage.removeItem(key);
}

/**
 *
 * @param {*} n 数值
 */
export const digitUpper = (n) => {
  const fraction = ['角', '分'];
	const digit = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
	const unit = [
		['元', '万', '亿'],
		['', '拾', '佰', '仟']
	];
	let value = n < 0 ? '负' : '';
	n = Math.abs(n);
	let s = "";
	for(let i = 0;i < fraction.length;i++) {
		s += (digit[Math.floor(n * 10 * Math.pow(10, i)) % 10] + fraction[i]).replace(/零./, '');
	}
	s = s || '整';
	n = Math.floor(n);
	for(let i = 0;i < unit[0].length && n > 0;i++) {
		let m = '';
		for(let j = 0;j < unit[1].length && n > 0;j++) {
			m = digit[n % 10] + unit[1][j] + m;
			n = Math.floor(n / 10);
		}
		s = m.replace(/(零.)*零$/, '').replace(/^$/, '零') + unit[0][i] + s;
	}
	return value + s.replace(/(零.)*零元/, '元').replace(/(零.)+/g, '零').replace(/^整$/, '零元整');
}


// thousand formatter
export const thousandsFormat = (n) => {
	if (n === '' || n === null || n === undefined) return;

	let isNegative = Math.sign(n) === -1,
		nums = (isNegative ? Math.abs(n) : n).toString(),
		res = '';

	nums = nums.split('.');
	while (nums[0].length > 3) {
		res = ',' + nums[0].slice(-3) + res;
		nums[0] = nums[0].slice(0, nums[0].length - 3);
	}
	if (nums[0]) { res = nums[0] + res };
	if (nums[1]) { res = res + '.' + nums[1] };
	return isNegative ? `-${res}` : res;
}

export const isEmpty = (val) => val == '' || val == null || val == undefined;
